﻿using System;
using System.Globalization;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace ICodeShare.UI.Converters
{
    #region IValueConverter
    /// <summary>
    /// Byte[]值转换成BitmapImage值
    /// </summary>
    /// <example>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///   xmlns:cvts="http://schemas.extended.wpf.com/converters"
    /// 2.在xaml文件添加Resources。
    ///   <Window.Resources>
    ///   <cvts:ByteToBitmapImageConverter x:Key="cvtsByteToBitmapImage"/>
    ///   </Window.Resources>
    /// 3.在xaml文件中指定Binding值的Converter
    ///    <Image Source="{Binding photo,Converter={StaticResource cvtsByteToBitmapImage}"></TextBox>
    /// </example>
    [ValueConversion(typeof(byte[]), typeof(BitmapImage))]
    public sealed class ByteToBitmapImageConverter : IValueConverter
    {
        #region Members
        /// <summary>
        /// 默认图片
        /// </summary>
        private string _defaultImage = string.Empty;
        #endregion

        #region Construction
        /// <summary>
        /// 
        /// </summary>
        public ByteToBitmapImageConverter()
        {

        }

        /// <summary>
        /// 实例化一个BooleanToVisibilityConverter类
        /// </summary>
        /// <param name="defaultImage">默认图片路径</param>
        public ByteToBitmapImageConverter(string defaultImage)
        {
            this.DefaultImage = defaultImage;
        }
        #endregion

        #region Properties
        /// <summary>
        /// 默认照片
        /// </summary>
        public string DefaultImage
        {
            get { return this._defaultImage; }
            set { this._defaultImage = value; }
        }
        #endregion

        #region  Base Class Overrides 基类方法重写
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        { 
            BitmapImage tempImage = null;
            byte[] tempImageData = null;

            if (value is byte[])
            {
                tempImageData = (byte[])value;
            }

            if (tempImageData != null && tempImageData.Length > 0)
            {
                tempImage = new BitmapImage();
                tempImage.BeginInit();
                tempImage.StreamSource = new MemoryStream(tempImageData);
                tempImage.EndInit();
            }
            else
            {
                if (!string.IsNullOrEmpty(this.DefaultImage))
                {
                    tempImage = new BitmapImage(new Uri(this.DefaultImage, UriKind.RelativeOrAbsolute));
                }
            }
            return tempImage;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
        #endregion
    }
    #endregion
}
